package lock;

import org.junit.Test;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 买票案例
 *
 * @author codefish
 * @version 1.0
 * @date 2022/08/04 下午 05:17
 */
public class SaleTicketDemo {


    @Test
    public void test() {
        TicketService ticketService = new TicketService();
        new Thread(() -> { while (true){ ticketService.saleTicket(); } },"a").start();
        new Thread(() -> { while (true){ ticketService.saleTicket(); } },"b").start();
        new Thread(() -> { while (true){ ticketService.saleTicket(); } },"c").start();

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }




    private static class TicketService {
        int remain = 5000;
//        ReentrantLock lock = new ReentrantLock();
        ReentrantLock lock = new ReentrantLock(true);

        public void saleTicket() {
            lock.lock();
            try {
                if (remain > 0) {
                    System.out.printf("[%s]卖出一张票，剩余%d张%n", Thread.currentThread().getName(), --remain);
                } else {
                    System.out.printf("[%s]卖完了。。。",Thread.currentThread().getName());
                    throw new RuntimeException("over");
                }
            } finally {
                lock.unlock();
            }
        }
    }

}
